using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using AuthService.Application.Services;
using AuthService.Domain.Enums;
using System.Text.Json;

namespace AuthService.Api.Controllers;

/// <summary>
/// 动态端点控制器 - 提供对动态生成的API端点的访问
/// 这个控制器会出现在Swagger文档中，方便测试动态API
/// </summary>
[ApiController]
[Route("api/dynamic")]
[Produces("application/json")]
[AllowAnonymous]
public class DynamicEndpointsController : ControllerBase
{
    private readonly IDynamicApiService _dynamicApiService;
    private readonly IUserServiceSimplified _userService;
    private readonly ILogger<DynamicEndpointsController> _logger;

    public DynamicEndpointsController(
        IDynamicApiService dynamicApiService,
        IUserServiceSimplified userService,
        ILogger<DynamicEndpointsController> logger)
    {
        _dynamicApiService = dynamicApiService;
        _userService = userService;
        _logger = logger;
    }

    /// <summary>
    /// 获取所有用户
    /// </summary>
    /// <returns>用户列表</returns>
    [HttpGet("users/usersasync")]
    [ProducesResponseType(typeof(IEnumerable<object>), 200)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> GetUsersAsync()
    {
        try
        {
            var (users, totalCount) = await _userService.GetUsersAsync();
            return Ok(new { users, totalCount });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取用户列表失败");
            return StatusCode(500, new { error = "获取用户列表失败", message = ex.Message });
        }
    }

    /// <summary>
    /// 根据ID获取用户
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <returns>用户信息</returns>
    [HttpGet("users/userbyidasync/{id}")]
    [ProducesResponseType(typeof(object), 200)]
    [ProducesResponseType(404)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> GetUserByIdAsync(Guid id)
    {
        try
        {
            var user = await _userService.GetUserByIdAsync(id);
            if (user == null)
            {
                return NotFound(new { error = "用户不存在", userId = id });
            }
            return Ok(user);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "根据ID获取用户失败: {UserId}", id);
            return StatusCode(500, new { error = "获取用户失败", message = ex.Message });
        }
    }

    /// <summary>
    /// 根据用户名获取用户
    /// </summary>
    /// <param name="username">用户名</param>
    /// <returns>用户信息</returns>
    [HttpGet("users/userbyusernameasync")]
    [ProducesResponseType(typeof(object), 200)]
    [ProducesResponseType(404)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> GetUserByUsernameAsync([FromQuery] string username)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(username))
            {
                return BadRequest(new { error = "用户名不能为空" });
            }

            var user = await _userService.GetUserByUsernameAsync(username);
            if (user == null)
            {
                return NotFound(new { error = "用户不存在", username });
            }
            return Ok(user);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "根据用户名获取用户失败: {Username}", username);
            return StatusCode(500, new { error = "获取用户失败", message = ex.Message });
        }
    }

    /// <summary>
    /// 根据邮箱获取用户
    /// </summary>
    /// <param name="email">邮箱地址</param>
    /// <returns>用户信息</returns>
    [HttpGet("users/userbyemailasync")]
    [ProducesResponseType(typeof(object), 200)]
    [ProducesResponseType(404)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> GetUserByEmailAsync([FromQuery] string email)
    {
        try
        {
            if (string.IsNullOrWhiteSpace(email))
            {
                return BadRequest(new { error = "邮箱地址不能为空" });
            }

            var user = await _userService.GetUserByEmailAsync(email);
            if (user == null)
            {
                return NotFound(new { error = "用户不存在", email });
            }
            return Ok(user);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "根据邮箱获取用户失败: {Email}", email);
            return StatusCode(500, new { error = "获取用户失败", message = ex.Message });
        }
    }

    /// <summary>
    /// 创建用户
    /// </summary>
    /// <param name="request">创建用户请求</param>
    /// <returns>创建的用户信息</returns>
    [HttpPost("users/userasync")]
    [ProducesResponseType(typeof(object), 201)]
    [ProducesResponseType(400)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> CreateUserAsync([FromBody] CreateUserRequest request)
    {
        try
        {
            if (request == null)
            {
                return BadRequest(new { error = "请求数据不能为空" });
            }

            if (string.IsNullOrWhiteSpace(request.Username))
            {
                return BadRequest(new { error = "用户名不能为空" });
            }

            if (string.IsNullOrWhiteSpace(request.Email))
            {
                return BadRequest(new { error = "邮箱不能为空" });
            }

            if (string.IsNullOrWhiteSpace(request.Password))
            {
                return BadRequest(new { error = "密码不能为空" });
            }

            var user = await _userService.CreateUserAsync(request.Username, request.Email, request.Password, request.DisplayName);

            // 返回创建成功的响应，包含用户信息和访问链接
            var response = new
            {
                message = "用户创建成功",
                user = new
                {
                    id = user.Id,
                    username = user.Username,
                    email = user.Email,
                    displayName = user.DisplayName,
                    createdAt = user.CreatedAt
                },
                links = new
                {
                    self = $"/api/dynamic/users/userbyidasync/{user.Id}",
                    all_users = "/api/dynamic/users/usersasync"
                }
            };

            return StatusCode(201, response);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建用户失败: {Username}", request?.Username);
            return StatusCode(500, new { error = "创建用户失败", message = ex.Message });
        }
    }

    /// <summary>
    /// 更新用户
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <param name="request">更新用户请求</param>
    /// <returns>更新的用户信息</returns>
    [HttpPut("users/userasync/{id}")]
    [ProducesResponseType(typeof(object), 200)]
    [ProducesResponseType(400)]
    [ProducesResponseType(404)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> UpdateUserAsync(Guid id, [FromBody] UpdateUserRequest request)
    {
        try
        {
            if (request == null)
            {
                return BadRequest(new { error = "请求数据不能为空" });
            }

            var existingUser = await _userService.GetUserByIdAsync(id);
            if (existingUser == null)
            {
                return NotFound(new { error = "用户不存在", userId = id });
            }

            // 更新用户信息
            if (!string.IsNullOrWhiteSpace(request.DisplayName))
                existingUser.DisplayName = request.DisplayName;
            if (!string.IsNullOrWhiteSpace(request.Email))
                existingUser.Email = request.Email;

            var updatedUser = await _userService.UpdateUserAsync(existingUser);
            return Ok(updatedUser);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "更新用户失败: {UserId}", id);
            return StatusCode(500, new { error = "更新用户失败", message = ex.Message });
        }
    }

    /// <summary>
    /// 删除用户
    /// </summary>
    /// <param name="id">用户ID</param>
    /// <returns>删除结果</returns>
    [HttpDelete("users/userasync/{id}")]
    [ProducesResponseType(200)]
    [ProducesResponseType(404)]
    [ProducesResponseType(500)]
    public async Task<IActionResult> DeleteUserAsync(Guid id)
    {
        try
        {
            var existingUser = await _userService.GetUserByIdAsync(id);
            if (existingUser == null)
            {
                return NotFound(new { error = "用户不存在", userId = id });
            }

            await _userService.DeleteUserAsync(id);
            return Ok(new { message = "用户删除成功", userId = id });
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "删除用户失败: {UserId}", id);
            return StatusCode(500, new { error = "删除用户失败", message = ex.Message });
        }
    }


}

/// <summary>
/// 创建用户请求模型
/// </summary>
public class CreateUserRequest
{
    /// <summary>
    /// 用户名
    /// </summary>
    public string Username { get; set; } = string.Empty;

    /// <summary>
    /// 邮箱地址
    /// </summary>
    public string Email { get; set; } = string.Empty;

    /// <summary>
    /// 密码
    /// </summary>
    public string Password { get; set; } = string.Empty;

    /// <summary>
    /// 显示名称
    /// </summary>
    public string? DisplayName { get; set; }
}

/// <summary>
/// 更新用户请求模型
/// </summary>
public class UpdateUserRequest
{
    /// <summary>
    /// 用户名
    /// </summary>
    public string? Username { get; set; }

    /// <summary>
    /// 邮箱地址
    /// </summary>
    public string? Email { get; set; }

    /// <summary>
    /// 显示名称
    /// </summary>
    public string? DisplayName { get; set; }
}
